package bean.managed;

import entity.PickingOrderEntity;
import bean.managed.util.JsfUtil;
import bean.managed.util.PaginationHelper;
import bean.session.PickingOrderEntityFacade;

import entity.LocationQuantityEntity;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;

@ManagedBean(name = "pickingOrderEntityController")
@SessionScoped
public class PickingOrderEntityController implements Serializable {

    private PickingOrderEntity current = null;
    private DataModel items = null;
    @EJB
    private bean.session.PickingOrderEntityFacade ejbFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    @ManagedProperty(value = "#{completedGoodsEntityController}")
    CompletedGoodsEntityController completedGoodsEntityController;

    public PickingOrderEntityController() {
      
    }
    
    public PickingOrderEntity getCurrent() {
        return current;
    }

    public void setCurrent(PickingOrderEntity current) {
        System.out.println("current is set over here");
        this.current = current;
    }

    public CompletedGoodsEntityController getCompletedGoodsEntityController() {
        return completedGoodsEntityController;
    }

    public void setCompletedGoodsEntityController(CompletedGoodsEntityController completedGoodsEntityController) {
        this.completedGoodsEntityController = completedGoodsEntityController;
        this.completedGoodsEntityController.setPickingOrderEntityController(this);
    }

    public PickingOrderEntityFacade getEjbFacade() {
        return ejbFacade;
    }

    public void setEjbFacade(PickingOrderEntityFacade ejbFacade) {
        this.ejbFacade = ejbFacade;
    }

    public PickingOrderEntity getSelected() {
        if (current == null) {
            current = new PickingOrderEntity();
            selectedItemIndex = -1;
        }
        return current;
    }

    private PickingOrderEntityFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "/entities/pickingOrderEntity/List?faces-redirect=true";
    }

    public String prepareView() {
        current = (PickingOrderEntity) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        current = new PickingOrderEntity();
        selectedItemIndex = -1;
        return "Create";
    }

    public String create() {
        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PickingOrderEntityCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        current = (PickingOrderEntity) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public String update() {
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PickingOrderEntityUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        current = (PickingOrderEntity) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PickingOrderEntityDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        {
            items = new ListDataModel(getFacade().findAll());
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    @FacesConverter(forClass = PickingOrderEntity.class)
    public static class PickingOrderEntityControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            PickingOrderEntityController controller = (PickingOrderEntityController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "pickingOrderEntityController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Long getKey(String value) {
            java.lang.Long key;
            key = Long.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Long value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof PickingOrderEntity) {
                PickingOrderEntity o = (PickingOrderEntity) object;
                return getStringKey(o.getId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + PickingOrderEntityController.class.getName());
            }
        }
    }

    public void generatePickingLocations() {

        String productToPick = current.getProduct().getProductName();
        System.out.println(productToPick + "--Product To Pick");
        LocationQuantityEntity locationToPick = null;
        int pickQuantity = current.getReservation().getQuantity();
        System.out.println(current.getReservation().getQuantity() + "--Product Quantity");

        while (pickQuantity > 0) {
            locationToPick = firstToExpireLocation(productToPick);
            current.getLocationToQuantity().add(locationToPick);
            pickQuantity = pickQuantity - locationToPick.getQuantity();
            getFacade().edit(current);
        }

    }

    private LocationQuantityEntity firstToExpireLocation(String productName) {
        System.out.println(productName);
        Calendar firstToExpire = null;
        LocationQuantityEntity locationQuantityToPick = null;

        List<LocationQuantityEntity> allLocationQuantities = new ArrayList<LocationQuantityEntity>(this.getCompletedGoodsEntityController().getEjbFacade().findAllCG());
        for (LocationQuantityEntity locationQuantityEntity : allLocationQuantities) {
            if (productName.equals(locationQuantityEntity.getInventory().getBatch().getProduct().getProductName()) && !current.getLocationToQuantity().contains(locationQuantityEntity)) {
                System.out.println("here2" + current.getLocationToQuantity().size());
                if (firstToExpire == null || locationQuantityEntity.getInventory().getBatch().getExpiryDate().before(firstToExpire.getTime())) {
                    firstToExpire = Calendar.getInstance();
                    firstToExpire.setTime(locationQuantityEntity.getInventory().getBatch().getExpiryDate());
                    locationQuantityToPick = locationQuantityEntity;
                }
            }
        }
        System.out.println("here4" + locationQuantityToPick.getQuantity());
        return locationQuantityToPick;
    }
}
